package com.hangzhou.xyj.manager;

import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.TextView;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.utils.CharacterParser;
import com.hangzhou.xyj.utils.StringUtil;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author : neo.duan
 * @date : 	  2014-11-13
 * @desc :    按字母拼音索引排序
 */

public class PinYinSortManager {
    private Context mContext;
    private HashMap<String, Integer> alphaIndexer;//存放存在的汉语拼音首字母和与之对应的列表位置，根据首字母，寻找对应的位置
    private String[] sections;//存放存在的汉语拼音首字母
    private Handler handler;
    private OverlayThread overlayThread;
    private TextView overlay;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;

    public PinYinSortManager(Context context) {
        this.mContext = context;
        init();

    }

    private void init() {
        alphaIndexer = new HashMap<String, Integer>();
        characterParser = new CharacterParser();
        handler = new Handler();
        overlayThread = new OverlayThread();
        initOverlay();
    }

    //设置overlay不可见
    private class OverlayThread implements Runnable {

        @Override
        public void run() {
            overlay.setVisibility(View.GONE);
        }

    }

    /**
     * 处理排序界面
     *
     * @param position
     */
    public void handlerView(int position) {
        overlay.setText(sections[position]);
        overlay.setVisibility(View.VISIBLE);
        handler.removeCallbacks(overlayThread);
        //延迟一秒后执行，让overlay为不可见
        handler.postDelayed(overlayThread, 500);
    }

    //初始化汉语拼音首字母弹出提示框
    private void initOverlay() {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        overlay = (TextView) inflater.inflate(R.layout.layout_choose_letter_overlay, null);
        overlay.setVisibility(View.INVISIBLE);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                PixelFormat.TRANSLUCENT);
        WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        windowManager.addView(overlay, lp);
    }

    /**
     * 提供出去排序
     *
     * @param list    传入的集合
     * @param sortStr 需要排序的字段
     * @return
     */
    public List<Object> sortDatas(List<? extends Object> list, String sortStr) {
        sections = new String[list.size()];//存在的汉语拼音的首字母
        List<Object> mSortList = new ArrayList<>();//存放排序过后的数组
        //for循环只要是进行sortLetters变量的赋值
        for (int i = 0; i < list.size(); i++) {
            //当前汉语拼音首字母
            String currentStr = getAlpha(characterParser.getSelling(getter(list.get(i), sortStr)));
            String sortString = currentStr.substring(0, 1).toUpperCase();
            Object obj = list.get(i);
            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                //设置Model里面的sortLetters为大写的拼音首字母
                setter(obj, "sortLetters", sortString, String.class);
            } else {
                //若拼音首字母非英文，设置为“#”
                setter(obj, "sortLetters", "#", String.class);
            }
            mSortList.add(obj);
        }
        // 根据a-z进行排序
        pinyinComparator = new PinyinComparator();
        Collections.sort(mSortList, pinyinComparator);

        // 排序后记录首字母位置
        for (int i = 0; i < mSortList.size(); i++) {
            if (i == 0 && i == mSortList.size() - 1) {
                setter(mSortList.get(i), "isAreaFirst", true, boolean.class);
                setter(mSortList.get(i), "isLastOne", true, boolean.class);
            } else if (i == 0) {//第一个元素
                String postSortString = getter(mSortList.get(i + 1), "sortLetters");//后一个元素的拼音首字母
                String currentSortString = getter(mSortList.get(i), "sortLetters");//当前一个元素的拼音首字母
                if (!currentSortString.equals(postSortString))
                    setter(mSortList.get(i), "isAreaLast", true, boolean.class);
                setter(mSortList.get(i), "isAreaFirst", true, boolean.class);
            } else if (i == mSortList.size() - 1) {//最后一个元素
                String preSortString = getter(mSortList.get(i - 1), "sortLetters");//前一个元素的拼音首字母
                String currentSortString = getter(mSortList.get(i), "sortLetters");//当前一个元素的拼音首字母
                if (!currentSortString.equals(preSortString))
                    setter(mSortList.get(i), "isAreaFirst", true, boolean.class);
                setter(mSortList.get(i), "isLastOne", true, boolean.class);
            } else {//既不是第一个也不是最后一个元素
                String preSortString = getter(mSortList.get(i - 1), "sortLetters");//前一个元素的拼音首字母
                String postSortString = getter(mSortList.get(i + 1), "sortLetters");//后一个元素的拼音首字母
                String currentSortString = getter(mSortList.get(i), "sortLetters");//当前一个元素的拼音首字母
                if (!currentSortString.equals(preSortString))
                    setter(mSortList.get(i), "isAreaFirst", true, boolean.class);
                if (!currentSortString.equals(postSortString))
                    setter(mSortList.get(i), "isAreaLast", true, boolean.class);

            }
            //取当前排序的内容
            String currentStr = getter(mSortList.get(i), sortStr);
            //取前一个排序的内容
            String previewStr = (i - 1) >= 0 ? getter(mSortList.get(i - 1), sortStr) : " ";
            //当前汉语拼音首字母
            if (!previewStr.equals(currentStr)) {//前后不重复时
                String name = getter(mSortList.get(i), "sortLetters");//取拼音首字母
                alphaIndexer.put(name, i);
                sections[i] = name;
            }
        }

        return mSortList;
    }

    /**
     * @param
     * @return
     * @Description 若参数obj，name，jack，String.class，则表示：调用obj的setName（String name），name为jack，即：obj.setName("jack")
     * @author yaohuix
     * @date 2016/2/15 14:02
     */
    public void setter(Object obj, String attr, Object value,
                       Class<?> type) {
        try {
            // 第一个参数表示方法名称，setAge、setName,第二个参数表示类型，如int.class,String.class
            Method method = obj.getClass().getMethod("set" + initStr(attr),
                    type);
            method.invoke(obj, value);// 调用方法
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param
     * @return
     * @Description 若参数obj，name，则调用obj的getName方法
     * @author yaohuix
     * @date 2016/2/15 14:01
     */
    public String getter(Object obj, String attr) {// 调用getter方法
        try {
            Method method = obj.getClass().getMethod("get" + initStr(attr));// 此方法不需要参数，如：getName(),getAge()
            return (String) method.invoke(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @param
     * @return
     * @Description 将首字母大写返回
     * @author yaohuix
     * @date 2016/2/15 13:59
     */
    public String initStr(String old) {// 单词首字母大写
        if (StringUtil.isBlank(old)) {
            return "";
        }
        String str = old.substring(0, 1).toUpperCase() + old.substring(1);
        return str;
    }

    /**
     * 获取首字母，非英文返回 “#”；英文返回 大写的首字母；
     *
     * @param str
     * @return
     */
    private String getAlpha(String str) {
        if (str == null) {
            return "#";
        }

        if (str.trim().length() == 0) {
            return "#";
        }

        char c = str.trim().substring(0, 1).charAt(0);
        // 正则表达式，判断首字母是否是英文字母
        Pattern pattern = Pattern.compile("^[A-Za-z]+$");
        if (pattern.matcher(c + "").matches()) {
            return (c + "").toUpperCase();
        } else {
            return "#";
        }
    }

    /**
     * @param
     * @author yaohuix
     * @Description 自定义一个比较器
     * @return
     * @date 2016/2/15 13:59
     */
    public class PinyinComparator implements Comparator<Object> {
        @Override
        public int compare(Object o1, Object o2) {
            if (getter(o1, "sortLetters").equals("@")
                    || getter(o2, "sortLetters").equals("#")) {
                return -1;
            } else if (getter(o1, "sortLetters").equals("#")
                    || getter(o2, "sortLetters").equals("@")) {
                return 1;
            } else {
                return getter(o1, "sortLetters").compareTo(getter(o2, "sortLetters"));
            }
        }
    }

    public HashMap<String, Integer> getAlphaIndexer() {
        return alphaIndexer;
    }

    public void setAlphaIndexer(HashMap<String, Integer> alphaIndexer) {
        this.alphaIndexer = alphaIndexer;
    }
}
